<?php

namespace app\index\model;

use think\Model;
use think\Db;

class Admin extends Model
{
    public function login($data){
        $admin = db('users')->getByName($data['name']);
        if (!$admin){
            $phone = db('users')->getByPhone($data['name']);
            if (!$phone){
                return ['valid'=>0,'msg'=>'该用户不存在'];
            }
            $d = [
                'phone' => $data['name'],
                'password' => md5($data['password']),
                'status' => '1'
            ];
        }else{
            $d = [
                'name' => $data['name'],
                'password' => md5($data['password']),
                'status' => '1'
            ];
        }

			//能够查询到此用户,并对比数据库
			// $data['password']==md5($data['password']);

            $userInfo = db('users')->where($d)->find();
			if ($userInfo) {
                session('userid',$userInfo['id']);
                session('username',$userInfo['name']);
                return ['valid'=>1,'msg'=>'登录成功'];
			}else {
				return ['valid'=>0,'msg'=>'用户名或者密码不正确'];
			}
	}

	public function register($data){
		$user = [
			'name' => $data['name'],
            'phone' => $data['phone'],
			'password' => md5($data['password'])
		];
		$res = db('users')->insert($user);
		if($res){
			return ['valid'=>1,'msg'=>'注册成功'];
		}else{
			return ['valid'=>0,'msg'=>'注册失败'];
		}
	}

	public function edit($data){
		$user = db('users')->where(['id' => $data['id']])->find();
		if($user){
			// $edata = [
			// 	'name' => $data['name'],
			// 	'password' => md5($data['newpassword'])
			// ];
			$res = db('users')->where('id', $data['id'])->update(['name' => $data['name'], 'password' => md5($data['password'])]);
			if($res){
				return ['valid'=>1,'msg'=>'修改成功'];
			}else{
				return ['valid'=>0,'msg'=>'修改失败'];
			}
		}else{
			return ['valid'=>0,'msg'=>'用户名或者密码错误'];
		}
	}
}
